import os
import re
import shutil
import datetime


class BackupManager(object):

    """
    backupPath:     destination for completed backups
    tempPath:       temporary location for backups before copying to backupPath
    trimInterval:   backups to keep
    dateFormat:     string for date to use as directory
    dateFileFormat: date/filetype tag for naming backup files
    backupJobs:     defined backups with name, function to call and arguments
    tempFiles:      list of full paths for files to be copied to backupPath

    getFormattedFile() : create a file path in the format tempPath/name-date-time.tar.gz
    """

    def __init__(self, backupPath, interval):
        self.date = datetime.datetime.now()
        self.dateISO = self.date.isocalender()
        self.dateFormat = '{}-{}-{}'.format(self.date.year, str(self.date.month).zfill(2),
                                            str(self.date.day).zfill(2))
        self.dateFileFormat = '-{}T{}-{}.tar.gz'.format(self.dateFormat, str(self.date.hour).zfill(2),
                                                        str(self.date.minute).zfill(2))
        self.backupRootPath = backupPath
        self.backupPath = os.path.join(backupPath, self.dateFileFormat)
        self.trimInterval = interval
        self.datePattern = re.compile(r'^\d\d\d\d-\d\d-\d\d$')
        self.backupJobs = {}
        self.tempFiles = []

    def makeTempPath(self, path):
        self.tempPath = path
        os.makedirs(path)

    def rmTempPath(self):
        shutil.rmtree(self.tempPath)

    def getTempBackupFiles(self):
        self.tempFiles =  [os.path.join(self.tempPath, e) for e in os.listdir(self.tempPath)
                           if self.dateFileFormat in e]
        return self.tempFiles

    def copyToBackupPath(self, path):
        shutil.copy2(path, self.backupPath)

    def getBackupsToTrim(self):
        return [os.path.join(self.backupRootPath, e) for e in os.listdir(self.backupRootPath)
                if re.match(self.datePattern, e)
                and (self.date - datetime.datetime.strptime(e, '%Y-%m-%d')).days > 6]


    def getFormattedFile(self, name):
        return os.path.join(self.tempPath, (name + self.dateFileFormat))

    def addBackupJob(self, name, func, **kwargs):
        self.backupJobs[name] = {'function': func, 'kwargs': kwargs}

    def callBackupJob(self, name):
        self.backupJobs[name]['function'](**self.backupjobs[name]['kwargs'])

